import base64
import re
from io import BytesIO

from PIL import Image
import cv2
import numpy as np

# base64转cv2
def base64_to_cv2(base64_string):
    base64_string = re.sub('^data:image/.+;base64,', '', base64_string)
    image_data = base64.b64decode(base64_string)
    image_array = np.frombuffer(image_data, dtype=np.uint8)
    image_array = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    # image_array = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)
    # print(image_array.shape)
    # cv2.imshow("img", image_array)
    # cv2.waitKey(0)
    return image_array

def base64_to_pil(img_base64):
    """
    Convert base64 image data to PIL image
    """
    image_data = re.sub('^data:image/.+;base64,', '', img_base64)
    pil_image = Image.open(BytesIO(base64.b64decode(image_data)))
    return pil_image

def np_to_base64(img_np):
    """
    Convert numpy image (RGB) to base64 string
    """
    img = Image.fromarray(img_np.astype('uint8'), 'RGB')
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    return u"data:image/png;base64," + base64.b64encode(buffered.getvalue()).decode("ascii")

# 压缩图片
def compress_image(image, max_width=720, max_height=1280, quality=50):
    # 获取图片的原始尺寸
    height, width = image.shape[:2]

    # 检查图片尺寸并等比例缩小
    if width > max_width or height > max_height:
        aspect_ratio = width / height
        if width > height:
            new_width = max_width
            new_height = int(new_width / aspect_ratio)
        else:
            new_height = max_height
            new_width = int(new_height * aspect_ratio)
        image = cv2.resize(image, (new_width, new_height))
        # 压缩图片
        compression_params = [cv2.IMWRITE_JPEG_QUALITY, quality]
        _, compressed_image = cv2.imencode('.jpg', image, compression_params)
        image = cv2.imdecode(compressed_image, cv2.IMREAD_COLOR)
        return image
    else:
        # compression_params = [cv2.IMWRITE_JPEG_QUALITY, quality]
        # _, compressed_image = cv2.imencode('.jpg', image, compression_params)
        # image = cv2.imdecode(compressed_image, cv2.IMREAD_COLOR)
        return image
